from django.contrib.contenttypes.models import ContentType
from rest_framework.viewsets import ModelViewSet, generics
from django.db import transaction
from rest_framework import generics
from rest_framework.views import APIView
from utils.permission import IsMemberUser
from utils import response_error, response_ok
from utils.exception import CustomError
from utils.customer_modelviewset import CustomerViewSet
from apps.system.models import Upload, Log
from apps.member.models import MemberRecord
from .serializers import DiarySerializer
from .models import Diary


class DiaryCollectViewSet(APIView):
    permission_classes = (IsMemberUser,)

    def post(self, request, id):
        diary = Diary.objects.filter(pk=id).first()
        if not diary:
            return response_error('为找到对应的日志')

        member_record = MemberRecord.objects.filter(content_type=Diary.get_content_type(), object_id=id,
                                                    member=self.request.user, operate=MemberRecord.COLLECT).first()
        with transaction.atomic():
            if member_record:
                # 存在，删除
                diary.collect_count -= 1
                diary.save()
                member_record.delete()
                return response_ok()
            # 不存在，创建
            diary.collect_count += 1
            diary.save()
            MemberRecord.objects.create(content_type=Diary.get_content_type(), member=self.request.user,
                                        object_id=id, operate=MemberRecord.COLLECT, describe='收藏')
        return response_ok()


class DiarylikeViewSet(APIView):
    '''点赞'''
    permission_classes = (IsMemberUser,)

    def post(self, request, id):
        diary = Diary.objects.filter(pk=id).first()
        if not diary:
            return response_error('为找到对应的日志')

        with transaction.atomic():

            member_record = MemberRecord.objects.filter(content_type=Diary.get_content_type(), object_id=id,
                                                        member=self.request.user, operate=MemberRecord.LIKE).first()
            if member_record:
                # 存在，删除
                diary.like_count -= 1
                diary.save()
                member_record.delete()
                return response_ok()
            # 不存在，创建
            diary.like_count += 1
            diary.save()
            MemberRecord.objects.create(content_type=Diary.get_content_type(), member=self.request.user,
                                        object_id=id, operate=MemberRecord.LIKE, describe='点赞')
        return response_ok()


class DiaryDetailViewSet(generics.RetrieveAPIView):
    queryset = Diary.objects.filter(delete=False)
    serializer_class = DiarySerializer

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()

        with transaction.atomic():
            instance.browse_count += 1
            instance.save()
            # 保存浏览记录
            if self.request.user and self.request.user.is_authenticated:
                MemberRecord.objects.create(content_type=Diary.get_content_type(), member=self.request.user,
                                            object_id=instance.id, operate=MemberRecord.BROWSE, describe='浏览')

        return super(DiaryDetailViewSet, self).retrieve(request, *args, **kwargs)


class DiaryHotViewSet(generics.ListAPIView):
    '''热帖'''
    queryset = Diary.objects.filter(delete=False).order_by('-browse_count', '-like_count')
    serializer_class = DiarySerializer


class DiaryViewSet(CustomerViewSet):
    '''个人日志的增删查'''
    permission_classes = (IsMemberUser,)
    queryset = Diary.objects.filter(delete=False)
    serializer_class = DiarySerializer

    def filter_queryset(self, queryset):
        queryset = queryset.filter(user=self.request.user)
        return queryset

    def create(self, request, *args, **kwargs):
        try:
            content = request.data['content']
            with transaction.atomic():
                diary = Diary.objects.create(content=content, user=request.user)
                for file in list(request.FILES.keys()):
                    upload = Upload.objects.upload(request.user, request.FILES[file])
                    diary.images.add(upload)
                diary.save()
                MemberRecord.objects.create(content_type=Diary.get_content_type(), member=self.request.user,
                                            object_id=diary.id, operate=MemberRecord.INSERT, describe='发布了一篇日记')
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))

        return response_ok()

    def destroy(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                diary = self.get_object()
                diary.delete = True
                diary.save()
                Log.objects.addLog(request.user, Log.INSERT, '删除了日志(%d)' % diary.id)
        except Exception as e:
            return response_error(str(e))
        return response_ok()
